﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Linq.Expressions;
using XYAC.Framework.MonitorTireMaterialOnline.Context;
using XYAC.Framework.MonitorTireMaterialOnline.Entities;
using XYAC.Framework.MonitorTireMaterialOnline.Extensions;
using XYAC.Framework.MonitorTireMaterialOnline.IServices;
using XYAC.Framework.MonitorTireMaterialOnline.LocalData.Context;
using XYAC.Framework.MonitorTireMaterialOnline.LocalData.Models;
using XYAC.Framework.MonitorTireMaterialOnline.OracleRemoteDB;

namespace XYAC.Framework.MonitorTireMaterialOnline.Services
{
    public class LocalDataService : ServiceBase<int, LocalDataContext>, ILocalDataService
    {
        private const String __TABLE_DwlData = "DwlData";
        private const String __TABLE_LaserData = "LaserData";
        private const String __TABLE_SpecVal = "SpecVal";

        public LocalDataService(IOptionsMonitor<AppConfig> appConfig, ILogger<LocalDataService> logger, IServiceProvider provider) : base(appConfig, logger, provider)
        {
        }

        public bool CreateDb()
        {
            using (var scope = Provider.CreateScope())
            {

                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                return Db.Database.EnsureCreated();
            }
        }


        internal int DeleteSpecInfoSyncMappingEntity(IEnumerable<string> preRemoveSpecKey)
        {
            using (var scope = Provider.CreateScope())
            {

                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                var specs = Db.SpecInfoSyncMapping.Where(T => preRemoveSpecKey.Contains(T.SpecName));
                Db.SpecInfoSyncMapping.RemoveRange(specs);

                return Db.SaveChanges();
            }
        }

        internal IEnumerable<SpecInfoSyncMapping> GetSpecInfoSyncMappingEntity(string[] findedSpecNames)
        {
            using (var scope = Provider.CreateScope())
            {

                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                var specs = Db.SpecInfoSyncMapping.Where(T => findedSpecNames.Contains(T.SpecName));

                return specs;
            }
        }

        internal SpecInfoSyncMapping GetSpecInfoSyncMappingByName(string typeName)
        {
            using (var scope = Provider.CreateScope())
            {

                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                var specs = Db.SpecInfoSyncMapping.FirstOrDefault(T => typeName == T.SpecName);

                return specs;
            }
        }

        internal int Update(SpecInfoSyncMapping findedMapping)
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                Db.Update(findedMapping);
                return Db.SaveChanges();
            }
        }

        internal int Add(SpecInfoSyncMapping mappingEntity)
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                Db.Add(mappingEntity);
                return Db.SaveChanges();
            }
        }

        internal int DeleteSpecInfoSyncMapping(IEnumerable<string> preRemoveSpecKey)
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                var specinfos = Db.SpecInfoSyncMapping.Where(T => preRemoveSpecKey.Contains(T.SpecName));
                Db.RemoveRange(specinfos);
                return Db.SaveChanges();
            }
        }

        internal IEnumerable<SpecInfoSyncMapping> GetSpecInfoSyncMapping(string[] findedSpecNames)
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                var specinfos = Db.SpecInfoSyncMapping.Where(T => findedSpecNames.Contains(T.SpecName));
                return specinfos;
            }
        }


        /// <summary>
        /// 定期删除LocalRecord记录数据
        /// </summary>
        /// <param name="days"></param>
        /// <returns></returns>
        public int RemoveTimeovered(int days)
        {
            int ret = 0;
            using (var scope = Provider.CreateScope())
            {
                try
                {

                    var Db = scope.ServiceProvider.GetService<LocalDataContext>();

                    // 计算30天前的日期
                    var thresholdDate = DateTime.Now.AddDays(-30);

                    // 查询出 YB_LOT_INSPECT 在30天前的记录 
                    var oldInspect = Db.YB_LOT_INSPECT
                                            .Where(record => record.PLAN_DATE.HasValue && record.PLAN_DATE.Value < thresholdDate)
                                            .ToList();


                    if (oldInspect.Any())
                    {
                        // 删除这些记录
                        Db.YB_LOT_INSPECT.RemoveRange(oldInspect);
                    }
                    // 保存更改
                    ret = Db.SaveChanges();
                }
                catch (Exception ex)
                {
                    Logger?.LogError($"定期清理YB_LOT_INSPECT失败:{ex.Message}", ex);
                }
            }
            return ret;
        }



        internal int GetCount<T>() where T : class, new()
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                return Db.Set<T>().Count();
            }
        }
        internal async Task<List<T>> GetPageAsync<T>(
     int pageIndex,
     int pageSize,
     List<Expression<Func<T, bool>>> filterConditions = null,
     List<(Expression<Func<T, object>> KeySelector, bool Descending)> orderConditions = null)
     where T : class, new()
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();

                IQueryable<T> data = Db.Set<T>();

                // 应用过滤条件
                if (filterConditions != null)
                {
                    foreach (var condition in filterConditions)
                    {
                        data = data.Where(condition);
                    }
                }

                // 应用排序条件
                bool isOrdered = false;

                if (orderConditions != null && orderConditions.Any())
                {
                    foreach (var (KeySelector, Descending) in orderConditions)
                    {
                        if (!isOrdered)
                        {
                            data = Descending ? data.OrderByDescending(KeySelector) : data.OrderBy(KeySelector);
                            isOrdered = true;
                        }
                        else
                        {
                            var orderedData = (IOrderedQueryable<T>)data;
                            data = Descending ? orderedData.ThenByDescending(KeySelector) : orderedData.ThenBy(KeySelector);
                        }
                    }
                }

                // 确保 pageIndex 为非负数，且 pageSize 为正数
                if (pageIndex < 0)
                    throw new ArgumentOutOfRangeException(nameof(pageIndex), "pageIndex 必须为非负数。");
                if (pageSize <= 0)
                    throw new ArgumentOutOfRangeException(nameof(pageSize), "pageSize 必须为正数。");

                return await data.Skip(pageIndex * pageSize).Take(pageSize).ToListAsync();
            }
        }


        internal SpecInfoSyncMapping GetFirstSpecInfoSyncMapping(Func<SpecInfoSyncMapping, bool> condition)
        {
            using (var scope = Provider.CreateScope())
            {
                var Db = scope.ServiceProvider.GetService<LocalDataContext>();
                return Db.SpecInfoSyncMapping.FirstOrDefault(condition);
            }
        }


        public int SyncAppDataToLocal_YST_SpecVal(int RowData = 20)
        {

            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    var option = scope.ServiceProvider.GetService<IOptionsMonitor<AppConfig>>();
                    var Db = new CustomHisDataContext(option, DateOnly.FromDateTime(DateTime.Now.Date.AddDays(-1)));//此处应当使用实例化方式获取DBContext
                    if (!Db.GetDbFileCreated())
                    {
                        return 0;
                    }
                    var localHis = new CustomReportContext(option, DateOnly.FromDateTime(DateTime.Now.Date.AddDays(-1)));
                    if (!localHis.GetDbFileCreated())
                    {
                        return 0;
                    }


                    var localHisSpecValCount = localHis.SpecVal.Count();
                    if (localHisSpecValCount > 0)
                    {
                        minKey = localHis.SpecVal.Max(T => T.ID);

                    }
                    var appData = Db.SpecVal.Where(T => T.ID > minKey).OrderBy(T => T.ID).Take(RowData).ToList();
                    Db.Dispose();
                    if (appData.Count() == 0)
                    {
                        return 0;
                    }
                    using (var trans = localHis.Database.BeginTransaction())
                    {
                        try
                        {
                            localHis.Set<SpecValLocal>().AddRange(appData.Select(T => new SpecValLocal(T)));
                            var tempRet = localHis.SaveChanges();
                            trans.Commit();
                            ret = tempRet;
                        }
                        catch (Exception ex)
                        {
                            trans.Rollback();
                        }
                    }
                    localHis.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }

        public int SyncAppDataToLocal_YST_WeightData(int RowData = 20)
        {

            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    var option = scope.ServiceProvider.GetService<IOptionsMonitor<AppConfig>>();
                    var Db = new CustomHisDataContext(option, DateOnly.FromDateTime(DateTime.Now.Date.AddDays(-1)));//此处应当使用实例化方式获取DBContext
                    if (!Db.GetDbFileCreated())
                    {
                        return 0;
                    }
                    var localHis = new CustomReportContext(option, DateOnly.FromDateTime(DateTime.Now.Date.AddDays(-1)));
                    if (!localHis.GetDbFileCreated())
                    {
                        return 0;
                    }


                    var localHisWeightDataCount = localHis.WeightData.Count();
                    if (localHisWeightDataCount > 0)
                    {
                        minKey = localHis.WeightData.Max(T => T.ID);

                    }
                    var appData = Db.WeightData.Where(T => T.ID > minKey).OrderBy(T => T.ID).Take(RowData).ToList();
                    Db.Dispose();
                    if (appData.Count() == 0)
                    {
                        return 0;
                    }
                    using (var trans = localHis.Database.BeginTransaction())
                    {
                        try
                        {
                            localHis.Set<WeightDataLocal>().AddRange(appData.Select(T => WeightDataLocal.From(T)));
                            var tempRet = localHis.SaveChanges();
                            trans.Commit();
                            ret = tempRet;
                        }
                        catch (Exception ex)
                        {
                            trans.Rollback();
                        }
                    }
                    localHis.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }

        #region 上传今日数据

        public int SyncAppDataToLocal_SpecVal<TContext>(int RowData = 20) where TContext : ReportContext
        {

            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    var Db = scope.ServiceProvider.GetService<CurrentHisDataContext>();
                    var localHis = scope.ServiceProvider.GetService<TContext>();



                    var localHisSpecValCount = localHis.SpecVal.Count();
                    if (localHisSpecValCount > 0)
                    {
                        minKey = localHis.SpecVal.Max(T => T.ID);

                    }


                    var appData = Db.SpecVal.Where(T => T.ID > minKey).OrderBy(T => T.ID).Take(RowData).ToList();
                    if (appData.Count() == 0)
                    {
                        return 0;
                    }
                    using (var trans = localHis.Database.BeginTransaction())
                    {
                        try
                        {
                            localHis.Set<SpecValLocal>().AddRange(appData.Select(T => new SpecValLocal(T)));
                            var tempRet = localHis.SaveChanges();
                            trans.Commit();
                            ret = tempRet;
                        }
                        catch (Exception ex)
                        {
                            trans.Rollback();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex.InnerException ?? ex);
            }
            return ret;
        }
        public int SyncAppDataToLocal_WeightData<TContext>(int RowData = 20) where TContext : ReportContext
        {

            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    var Db = scope.ServiceProvider.GetService<CurrentHisDataContext>();
                    var localHis = scope.ServiceProvider.GetService<TContext>();



                    var localHisWeightDataCount = localHis.WeightData.Count();
                    if (localHisWeightDataCount > 0)
                    {
                        minKey = localHis.WeightData.Max(T => T.ID);

                    }


                    var appData = Db.WeightData.Where(T => T.ID > minKey).OrderBy(T => T.ID).Take(RowData).ToList();
                    if (appData.Count() == 0)
                    {
                        return 0;
                    }
                    using (var trans = localHis.Database.BeginTransaction())
                    {
                        try
                        {
                            localHis.Set<WeightDataLocal>().AddRange(appData.Select(T => WeightDataLocal.From(T)));
                            var tempRet = localHis.SaveChanges();
                            trans.Commit();
                            ret = tempRet;
                        }
                        catch (Exception ex)
                        {
                            trans.Rollback();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex.InnerException ?? ex);
            }
            return ret;
        }
        public int SyncSemiSteelSideInspectionReportToRemote<TContext>(int RowData = 20) where TContext : ReportContext
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    using (var Db = scope.ServiceProvider.GetService<CurrentReportContext>())
                    {
                        //远程数据库上下文
                        using (var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>())
                        {

                            var localReport = Db.SemiSteelSideInspectionReport.Where(T => T.SyncState != true).Include(T => T.SpecVal).OrderBy(T => T.ID).Take(20).ToList();
                            if (localReport.Count == 0)
                            {
                                return 0;
                            }
                            using (var localTrans = Db.Database.BeginTransaction())
                            {
                                try
                                {
                                    using (var remoteTrans = remoteDb.Database.BeginTransaction())
                                    {
                                        try
                                        {

                                            foreach (var row in localReport)
                                            {
                                                row.SyncState = true;
                                            }

                                            var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP()).ToList();
                                            processSteps.ForEach(T =>
                                            {
                                                T.EQP = this.AppConfig.CurrentValue.DetectionMachineNo;
                                                T.EQP_TYPE = this.AppConfig.CurrentValue.ManualUpload == true ? "0" : "1";
                                            });
                                            remoteDb.AddRange(processSteps);
                                            var tempRemote = remoteDb.SaveChanges();

                                            Db.UpdateRange(localReport);
                                            var tempLocal = Db.SaveChanges();

                                            if (tempLocal == tempRemote)
                                            {
                                                localTrans.Commit();
                                                remoteTrans.Commit();
                                                ret = tempRemote;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            localTrans.Rollback();
                                            remoteTrans.Rollback();
                                            Logger?.LogError(ex.Message, ex);
                                            throw;
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {

                                    localTrans.Rollback();
                                    Logger?.LogError(ex.Message, ex);
                                    throw;
                                }
                            }
                        }
                    }


                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }

        public int SyncSemiSteelTreadScanReportToRemote<TContext>(int RowData = 20) where TContext : ReportContext
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    using (var Db = scope.ServiceProvider.GetService<CurrentReportContext>())
                    {
                        //远程数据库上下文
                        using (var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>())
                        {
                            var localReport = Db.SemiSteelTreadScanReport.Where(T => T.SyncState == false).Include(T => T.SpecVal).OrderBy(T => T.ID).Take(RowData).ToList();
                            //var count1 = Db.SemiSteelTreadScanReport.Where(T => T.SyncState == false).Count();
                            //var count2 = Db.SemiSteelTreadScanReport.Where(T => T.SyncState != false).Count();
                            //var count3 = Db.SemiSteelTreadScanReport.Count();
                            //Debug.WriteLine($"totalCount:{count3} count1:{count1} count2:{count2}");
                            if (localReport.Count == 0)
                            {
                                return 0;
                            }
                            using (var localTrans = Db.Database.BeginTransaction())
                            {
                                try
                                {
                                    using (var remoteTrans = remoteDb.Database.BeginTransaction())
                                    {
                                        try
                                        {


                                            var processSteps = localReport.AsParallel().Select(T => T.ToYB_PROCESS_STEP()).ToList();
                                            foreach (var step in processSteps)
                                            {
                                                step.EQP = this.AppConfig.CurrentValue.DetectionMachineNo;
                                                step.EQP_TYPE = this.AppConfig.CurrentValue.ManualUpload == true ? "0" : "1";
                                            }
                                            remoteDb.AddRange(processSteps);
                                            var tempRemote = remoteDb.SaveChanges();


                                            foreach (var row in localReport)
                                            {
                                                row.SyncState = true;
                                            }

                                            Db.UpdateRange(localReport);
                                            var tempLocal = Db.SaveChanges();

                                            if (tempLocal == tempRemote)
                                            {
                                                localTrans.Commit();
                                                remoteTrans.Commit();
                                                ret = tempRemote;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            localTrans.Rollback();
                                            remoteTrans.Rollback();
                                            Logger?.LogError(ex.Message, ex);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {

                                    localTrans.Rollback();
                                    Logger?.LogError(ex.Message, ex);
                                }
                            }
                        }
                    }


                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }

        public int SyncSemiSteelTriangleRubberReportToRemote<TContext>(int RowData = 20) where TContext : ReportContext
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    var Db = scope.ServiceProvider.GetService<CurrentReportContext>();
                    //远程数据库上下文
                    var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>();

                    var localReport = Db.SemiSteelTriangleRubberReport.Where(T => T.SyncState == false).Include(T => T.SpecVal).OrderBy(T => T.ID).Take(20).ToList();
                    if (localReport.Count == 0)
                    {
                        return 0;
                    }
                    using (var localTrans = Db.Database.BeginTransaction())
                    {
                        try
                        {
                            using (var remoteTrans = remoteDb.Database.BeginTransaction())
                            {
                                try
                                {

                                    foreach (var row in localReport)
                                    {
                                        row.SyncState = true;
                                    }

                                    var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP()).ToList();
                                    processSteps.ForEach(T =>
                                    {
                                        T.EQP = this.AppConfig.CurrentValue.DetectionMachineNo;
                                        T.EQP_TYPE = this.AppConfig.CurrentValue.ManualUpload == true ? "0" : "1";
                                    });
                                    remoteDb.AddRange(processSteps);
                                    var tempRemote = remoteDb.SaveChanges();

                                    Db.UpdateRange(localReport);
                                    var tempLocal = Db.SaveChanges();

                                    if (tempLocal == tempRemote)
                                    {
                                        localTrans.Commit();
                                        remoteTrans.Commit();
                                        ret = tempRemote;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    localTrans.Rollback();
                                    remoteTrans.Rollback();
                                }
                            }
                        }
                        catch (Exception)
                        {

                            localTrans.Rollback();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }
        #endregion



        #region 上传昨日数据
        public int SyncSemiSteelSideInspectionReport_YST_ToRemote(int RowData = 20)
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    var Db = new CustomReportContext(this.AppConfig, DateOnly.FromDateTime(DateTime.Now.Date.AddDays(-1)));
                    //远程数据库上下文
                    var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>();

                    var localReport = Db.SemiSteelSideInspectionReport.Where(T => T.SyncState == false).Include(T => T.SpecVal).OrderBy(T => T.ID).Take(20).ToList();
                    if (localReport.Count == 0)
                    {
                        return 0;
                    }
                    using (var localTrans = Db.Database.BeginTransaction())
                    {
                        try
                        {
                            using (var remoteTrans = remoteDb.Database.BeginTransaction())
                            {
                                try
                                {

                                    foreach (var row in localReport)
                                    {
                                        row.SyncState = true;
                                    }

                                    var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP()).ToList();
                                    processSteps.ForEach(T =>
                                    {
                                        T.EQP = this.AppConfig.CurrentValue.DetectionMachineNo;
                                        T.EQP_TYPE = this.AppConfig.CurrentValue.ManualUpload == true ? "0" : "1";
                                    });
                                    remoteDb.AddRange(processSteps);
                                    var tempRemote = remoteDb.SaveChanges();

                                    Db.UpdateRange(localReport);
                                    var tempLocal = Db.SaveChanges();

                                    if (tempLocal == tempRemote)
                                    {
                                        localTrans.Commit();
                                        remoteTrans.Commit();
                                        ret = tempRemote;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    localTrans.Rollback();
                                    remoteTrans.Rollback();
                                }
                            }
                        }
                        catch (Exception)
                        {

                            localTrans.Rollback();
                        }
                    }
                    Db.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }

        public int SyncSemiSteelTreadScanReport_YST_ToRemote(int RowData = 20)
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    var Db = new CustomReportContext(this.AppConfig, DateOnly.FromDateTime(DateTime.Now.Date.AddDays(-1)));
                    //远程数据库上下文
                    var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>();

                    var localReport = Db.SemiSteelTreadScanReport.Where(T => T.SyncState == false).Include(T => T.SpecVal).OrderBy(T => T.ID).Take(20).ToList();
                    if (localReport.Count == 0)
                    {
                        return 0;
                    }
                    using (var localTrans = Db.Database.BeginTransaction())
                    {
                        try
                        {
                            using (var remoteTrans = remoteDb.Database.BeginTransaction())
                            {
                                try
                                {

                                    foreach (var row in localReport)
                                    {
                                        row.SyncState = true;
                                    }

                                    var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP()).ToList();
                                    processSteps.ForEach(T =>
                                    {
                                        T.EQP = this.AppConfig.CurrentValue.DetectionMachineNo;
                                        T.EQP_TYPE = this.AppConfig.CurrentValue.ManualUpload == true ? "0" : "1";
                                    });
                                    remoteDb.AddRange(processSteps);
                                    var tempRemote = remoteDb.SaveChanges();

                                    Db.UpdateRange(localReport);
                                    var tempLocal = Db.SaveChanges();

                                    if (tempLocal == tempRemote)
                                    {
                                        localTrans.Commit();
                                        remoteTrans.Commit();
                                        ret = tempRemote;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    localTrans.Rollback();
                                    remoteTrans.Rollback();
                                }
                            }
                        }
                        catch (Exception)
                        {

                            localTrans.Rollback();
                        }
                    }
                    Db.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }

        public int SyncSemiSteelTriangleRubberReport_YST_ToRemote(int RowData = 20)
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    var Db = new CustomReportContext(this.AppConfig, DateOnly.FromDateTime(DateTime.Now.Date.AddDays(-1)));
                    //远程数据库上下文
                    var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>();

                    var localReport = Db.SemiSteelTriangleRubberReport.Where(T => T.SyncState == false).Include(T => T.SpecVal).OrderBy(T => T.ID).Take(20).ToList();
                    if (localReport.Count == 0)
                    {
                        return 0;
                    }
                    using (var localTrans = Db.Database.BeginTransaction())
                    {
                        try
                        {
                            using (var remoteTrans = remoteDb.Database.BeginTransaction())
                            {
                                try
                                {

                                    foreach (var row in localReport)
                                    {
                                        row.SyncState = true;
                                    }

                                    var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP()).ToList();
                                    processSteps.ForEach(T =>
                                    {
                                        T.EQP = this.AppConfig.CurrentValue.DetectionMachineNo;
                                        T.EQP_TYPE = this.AppConfig.CurrentValue.ManualUpload == true ? "0" : "1";
                                    });
                                    remoteDb.AddRange(processSteps);
                                    var tempRemote = remoteDb.SaveChanges();

                                    Db.UpdateRange(localReport);
                                    var tempLocal = Db.SaveChanges();

                                    if (tempLocal == tempRemote)
                                    {
                                        localTrans.Commit();
                                        remoteTrans.Commit();
                                        ret = tempRemote;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    localTrans.Rollback();
                                    remoteTrans.Rollback();
                                }
                            }
                        }
                        catch (Exception)
                        {

                            localTrans.Rollback();
                        }
                    }
                    Db.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }

        public int SyncWeightDataToRemote<T>()
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    var Db = scope.ServiceProvider.GetService<CurrentReportContext>();
                    //远程数据库上下文
                    var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>();

                    var localReport = Db.WeightData.Where(T => T.SyncState == false).OrderBy(T => T.ID).Take(20).ToList();
                    if (localReport.Count == 0)
                    {
                        return 0;
                    }
                    using (var localTrans = Db.Database.BeginTransaction())
                    {
                        try
                        {
                            using (var remoteTrans = remoteDb.Database.BeginTransaction())
                            {
                                try
                                {

                                    foreach (var row in localReport)
                                    {
                                        row.SyncState = true;
                                    }

                                    var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP()).ToList();
                                    processSteps.ForEach(T =>
                                    {
                                        T.EQP = this.AppConfig.CurrentValue.DetectionMachineNo;
                                    });
                                    remoteDb.AddRange(processSteps);
                                    var tempRemote = remoteDb.SaveChanges();

                                    Db.UpdateRange(localReport);
                                    var tempLocal = Db.SaveChanges();

                                    if (tempLocal == tempRemote)
                                    {
                                        localTrans.Commit();
                                        remoteTrans.Commit();
                                        ret = tempRemote;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    localTrans.Rollback();
                                    remoteTrans.Rollback();
                                }
                            }
                        }
                        catch (Exception)
                        {

                            localTrans.Rollback();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }

        public int SyncWeightData_YST_ToRemote()
        {
            int ret = 0;
            try
            {
                using (var scope = Provider.CreateScope())
                {
                    int? minKey = 0;
                    //当前报表数据库上下文
                    var Db = new CustomReportContext(this.AppConfig, DateOnly.FromDateTime(DateTime.Now.Date.AddDays(-1)));
                    //远程数据库上下文
                    var remoteDb = scope.ServiceProvider.GetService<OracleMesContext>();

                    var localReport = Db.WeightData.Where(T => T.SyncState == false).OrderBy(T => T.ID).Take(20).ToList();
                    if (localReport.Count == 0)
                    {
                        return 0;
                    }
                    using (var localTrans = Db.Database.BeginTransaction())
                    {
                        try
                        {
                            using (var remoteTrans = remoteDb.Database.BeginTransaction())
                            {
                                try
                                {

                                    foreach (var row in localReport)
                                    {
                                        row.SyncState = true;
                                    }

                                    var processSteps = localReport.Select(T => T.ToYB_PROCESS_STEP()).ToList();
                                    processSteps.ForEach(T =>
                                    {
                                        T.EQP = this.AppConfig.CurrentValue.DetectionMachineNo;
                                    });
                                    remoteDb.AddRange(processSteps);
                                    var tempRemote = remoteDb.SaveChanges();

                                    Db.UpdateRange(localReport);
                                    var tempLocal = Db.SaveChanges();

                                    if (tempLocal == tempRemote)
                                    {
                                        localTrans.Commit();
                                        remoteTrans.Commit();
                                        ret = tempRemote;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    localTrans.Rollback();
                                    remoteTrans.Rollback();
                                }
                            }
                        }
                        catch (Exception)
                        {

                            localTrans.Rollback();
                        }
                    }
                    Db.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
            return ret;
        }
        #endregion
    }
}
